package com.IntelligentCommunity.dataAccess.service.impl;

import com.IntelligentCommunity.algorithm.api.AlgorithmRemote;
import com.IntelligentCommunity.algorithm.domain.FaceRecognitionConf;
import com.IntelligentCommunity.common.core.domain.R;
import com.IntelligentCommunity.common.core.utils.StringUtils;
import com.IntelligentCommunity.common.core.utils.uuid.UUID;
import com.IntelligentCommunity.community.api.RemoteDistrictService;
import com.IntelligentCommunity.community.api.RemoteDoorService;
import com.IntelligentCommunity.community.api.RemoteFacilitiesService;
import com.IntelligentCommunity.community.domain.RealDoor;
import com.IntelligentCommunity.community.domain.RealSecurityFacilities;
import com.IntelligentCommunity.dataAccess.domain.Base64MultiPartFile;
import com.IntelligentCommunity.dataAccess.domain.FaceCapture;
import com.IntelligentCommunity.dataAccess.domain.VehicleCapture;
import com.IntelligentCommunity.dataAccess.service.ICaptureService;
import com.IntelligentCommunity.file.api.RemoteFileService;
import com.IntelligentCommunity.file.domain.SysFile;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

import static com.IntelligentCommunity.common.core.constant.KafkaNames.*;

/**
 * @Author：ZHP
 * @Package：com.IntelligentCommunity.service.impl
 * @Project：IntelligentCommunity
 * @name：CaptureServiceImpl
 * @Date：2024/7/19 00:56
 * @Filename：CaptureServiceImpl
 */
@Service
@Log4j2
public class CaptureServiceImpl implements ICaptureService {

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    @Autowired
    private AlgorithmRemote algorithmRemote;

    @Autowired
    private RemoteDistrictService districtService;

    @Autowired
    private RemoteFacilitiesService facilitiesService;

    @Autowired
    private RemoteFileService remoteFileService;
    @Autowired
    private RemoteDoorService remoteDoorService;


    @Transactional
    @Override
    public void faceCapture(FaceCapture faceCapture) {
        faceCapture.setId(12L);
        try {
            String img = faceCapture.getImage();


            HashMap<String, Object> hashMap = new HashMap<>();

            // 上传图片到服务器
            File file = decodeBase64ToFile(img);
            MultipartFile multiPartFile = new Base64MultiPartFile(file);

            R<SysFile> upload = remoteFileService.upload(multiPartFile);


            // 准备人脸识别配置
            FaceRecognitionConf faceRecognitionConf = new FaceRecognitionConf();
            faceRecognitionConf.setImg(upload.getData().getUrl());

            // 调用远程算法服务进行人脸识别
            R r = algorithmRemote.faceDet(faceRecognitionConf);
            Map<String, Object> data = (Map) r.getData();

            // 检查结果是否包含"result"字段
            if (data.containsKey("result")) {
                Object result = data.get("result");

                // 将结果转换为JSON字符串
                String jsonString = JSONObject.toJSONString(result);

                // 解析JSON字符串为List<Map>
                List<Map> maps = JSONObject.parseArray(jsonString, Map.class);

                Map map = maps.get(0);

                // 检查map是否包含"gender", "age", 和 "subjects"
                if (map.containsKey("gender") && map.containsKey("age")) {
                    Object gender = map.get("gender");
                    Object age = map.get("age");
                    Object mask = map.get("mask");

                    // 将性别和年龄信息添加到hashMap中
                    hashMap.put("gender", gender);
                    // 将subjects字段添加到hashMap中
                    hashMap.put("age", age);
                    // 将mask字段添加到hashMap中
                    hashMap.put("mask", mask);

                }


                // 将dateTime字段添加到hashMap中
                hashMap.put("dateTime", faceCapture.getDateTime());
                // 将realSecurityFacilitiesId字段添加到hashMap中
                hashMap.put("realSecurityFacilitiesId", faceCapture.getId());

                RealSecurityFacilities facilities = facilitiesService.getSecurityFacilitiesInfoById(faceCapture.getId()).getData();
                if (facilities.getDistrictId() == null) {
                    throw new RuntimeException("设备不存在");

                }
                    hashMap.put("districtId", facilities.getDistrictId());
                    hashMap.put("districtName", facilities.getCommunityName());




                // 将image字段添加到hashMap中
                hashMap.put("image", upload.getData().getUrl());
                // 人脸比对
                kafkaTemplate.send(TOPIC_NAME_FACE_BASE64, UUID.randomUUID().toString(), hashMap);

                log.info("发送成功");


            }
        } catch (ClassCastException e) {
            log.error("类型转换错误：{}", e.getMessage());
        } catch (JSONException e) {
            log.error("JSON解析错误：{}", e.getMessage());
        }


    }
    @Transactional
    @Override
    public void carCapture(VehicleCapture vehicleCapture) {
        kafkaTemplate.send(TOPIC_TOPIC_NAME_CAR, UUID.randomUUID().toString(),vehicleCapture);
    }
    @Transactional
    @Override
    public void faceCaptureAsd(FaceCapture faceCapture) {
        kafkaTemplate.send(TOPIC_NAME_NAME_IMG, UUID.randomUUID().toString(),faceCapture);
        log.info("发送成功");
    }

    @Override
    public void doorCapture(RealDoor realDoor) {
        if (realDoor == null){
            throw new RuntimeException("数据不能为空");
        }
        remoteDoorService.add(realDoor);
    }

    private File decodeBase64ToFile(String base64String) {
        try {
            // 创建一个临时文件
            File tempFile = File.createTempFile("tempFile", ".png");
            tempFile.deleteOnExit(); // 程序结束时删除临时文件

            // 去掉可能存在的空格和换行
            String cleanedBase64 = base64String.replaceAll("\\s+", "");

            // 解码 Base64 字符串
            byte[] data = Base64.getDecoder().decode(cleanedBase64);

            // 写入数据到文件
            FileOutputStream fos = new FileOutputStream(tempFile);
            fos.write(data);
            fos.flush();
            // 返回生成的 File 对象
            return tempFile;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("base64转图片失败");
        }

    }

}
